
<template>
  <div class="dashboard-container">
    <div class="app-container">
      <page-tools :show-before="true">
        <span slot="before">共166条记录</span>
        <template slot="after">
          <el-button size="small" type="warning" @click="$router.push('/import')">导入</el-button>
          <el-button size="small" type="danger" @click="exportExcel">导出</el-button>
          <el-button v-if="checkPerm('addEmployee')" size="small" type="primary" @click="isShowDialog = true">新增员工</el-button>
        </template>
      </page-tools>
      <!-- 放置表格和分页 -->
      <el-card>
        <el-table border :data="employeeList">
          <el-table-column label="序号" sortable="" type="index" :index="customIndex" />
          <el-table-column sortable="" label="头像" width="200">
            <template v-slot="scoped">
              <img
                v-fiximg="require('@/assets/common/head.jpg')"
                :src="scoped.row.staffPhoto"
                alt=""
                class="avatar"
              >
            </template>
          </el-table-column>
          <el-table-column label="姓名" sortable="" prop="username" />
          <el-table-column label="手机" sortable="" prop="mobile" />
          <el-table-column label="工号" sortable="" prop="workNumber" />
          <el-table-column
            label="聘用形式"
            sortable=""
            prop="formOfEmployment"
            :formatter="formatEmployment"
          />
          <el-table-column label="部门" sortable="" prop="departmentName" />
          <el-table-column label="入职时间" sortable="">
            <template v-slot="scoped">
              {{ scoped.row.timeOfEntry | formatDate }}
            </template>
          </el-table-column>
          <el-table-column label="账户状态" sortable="" prop="enableState">
            <template v-slot="scoped">
              <el-switch v-model="scoped.row.enableState" :active-value="1" :inactive-value="2" disabled />
            </template>
          </el-table-column>
          <el-table-column label="操作" sortable="" fixed="right" width="280">
            <template v-slot="scoped">
              <el-button type="text" size="small" @click="$router.push('/employees/detail/' + scoped.row.id)">查看</el-button>
              <el-button type="text" size="small">转正</el-button>
              <el-button type="text" size="small">调岗</el-button>
              <el-button type="text" size="small">离职</el-button>
              <el-button type="text" size="small" @click="assignRole(scoped.row.id)">角色</el-button>
              <el-button type="text" size="small" @click="delEmployee(scoped.row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页组件 -->
        <el-row
          type="flex"
          justify="center"
          align="middle"
          style="height: 60px"
        >
          <el-pagination
            layout="prev, pager, next"
            :total="total"
            :page-size="pageConfig.size"
            @current-change="currentChange"
          />
        </el-row>
      </el-card>
      <AddEmployee :is-show-dialog="isShowDialog" />
      <AssignRole ref="assignRole" :is-show-dialog.sync="isShowRole" />
    </div>
  </div>
</template>

<script>
import AssignRole from './components/assign-role.vue'
import { formatDate } from '@/filters'
import { export_json_to_excel } from '@/vendor/Export2Excel'
import AddEmployee from './components/add-employee.vue'
import { getEmployee, delEmployee } from '@/api/employees'
import EmployeeEnum from '@/api/constant/employees'
export default {
  components: {
    AddEmployee,
    AssignRole
  },
  data() {
    return {
      pageConfig: {
        page: 1,
        size: 5
      },
      employeeList: [],
      total: 0,
      isShowDialog: false,
      isShowRole: false
    }
  },
  created() {
    this.loadPage()
  },
  methods: {
    async loadPage() {
      const { rows, total } = await getEmployee(this.pageConfig)
      this.total = total
      // this.employeeList=rows
      // console.log(rows);
      // 这里后端的数据跟我们的预期不一样, 可以造些假数据测试功能
      // 1. 日期希望是完整的日期字符串
      // 2. 账号状态希望有数据
      this.employeeList = rows.map((user) => {
        const date = new Date()
        return {
          ...user,
          timeOfEntry: date.toString(),
          enableState: 1
        }
      })
    },
    currentChange(newPage) {
      this.pageConfig.page = newPage
      this.loadPage()
    },
    formatEmployment(row, col, cell) {
      // 这个函数会在当前列的每个格子执行, 自动得到以下形参
      // row 行数据, col 列数据, cell 格子数据, index 索引
      // 格式化函数的特点是, 会议这个函数的返回值替换原来的数据
      // return cell === 1 ? '正式工' : '临时工'
      // 将所有可能性列举出来的数据格式, 叫做枚举
      // const hireType = [
      //   { id: 1, value: '正式员工' },
      //   { id: 2, value: '临时员工' }
      // ]
      const res = EmployeeEnum.hireType.find(
        (time) => Number(time.id) === Number(cell)
      )
      return res ? res.value : '未知形式'
    },
    customIndex(index) {
      // 索引应该等于前面的所有数据数量
      // 继续往下加
      // 前面所有数量=上一页页码*每页长度
      // 比如现在在第三页每页5条, 之前就有 2 * 5 共 10 数据
      // 接下来就是 11 12 13 ...
      return (this.pageConfig.page - 1) * this.pageConfig.size + index + 1
    },
    async delEmployee(id) {
      await this.$confirm('是否确定删除')
      await delEmployee(id)
      this.$message.success('删除成功')
      this.loadPage()
    },
    async exportExcel() {
      // 1. 获取全部员工
      const { rows } = await getEmployee({ page: 1, size: this.total })
      // console.log(rows)
      // 2. 演示生成 excel 的库
      // export_json_to_excel({
      //   header: ['姓名', '年龄', '地址'],
      //   data: [
      //     ['tom', 12, '珠吉路'],
      //     ['小陈', 19, '吉山幼儿园']
      //   ]
      // })

      // 3. 数据转换
      const dict = {
        '手机号': 'mobile',
        '姓名': 'username',
        '入职日期': 'timeOfEntry',
        '聘用形式': 'formOfEmployment',
        '转正日期': 'correctionTime',
        '工号': 'workNumber',
        '部门': 'departmentName'
      }
      // 用 Object.keys 获取对象 key 组成表头
      const header = Object.keys(dict)
      // console.log('表头', header)

      // 将用户对象转成用户数组
      const data = rows.map(user => {
        const arr = []
        for (const key in dict) {
          // 本来只是直接往里放, 但是如果遇到聘用形式或者时间
          // 需要特殊处理
          if (dict[key] === 'formOfEmployment') {
            // 聘用形式
            const val = user[dict[key]]
            const res = EmployeeEnum.hireType.find(item => item.id === val)
            arr.push(res ? res.value : '未知')
          } else if (dict[key] === 'timeOfEntry' || dict[key] === 'correctionTime') {
            // 处理时间
            const val = user[dict[key]]
            arr.push(formatDate(val))
          } else {
            // 其他情况
            arr.push(user[dict[key]])
          }
        }
        return arr
      })

      // 3. 调用生成工具下载 excel
      export_json_to_excel({
        header,
        data
      })
    },
    async assignRole(id) {
      await this.$refs.assignRole.getRoleIds(id)
      this.isShowRole = true
    }
  }
}
</script>

<style lang="scss" scoped>
.avatar {
  width: 180px;
  height: 80px;
  // object-fit:contain;
  object-fit: cover;
}
</style>
